package com.webside.points.controller;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.webside.points.model.AnswerEntity;
import com.webside.points.model.IssueEntity;
import com.webside.points.model.LikeEntity;
import com.webside.points.model.UserEntity;
import com.webside.points.service.AnswerService;
import com.webside.points.service.ExpertService;
import com.webside.points.service.IssueService;
import com.webside.points.service.LikeService;
import com.webside.points.service.UserService;
import com.webside.points.wechat.Constant;
import com.webside.points.wechat.WeChatConfig;
import com.webside.points.wechat.Wechat;

@Controller
@Scope("prototype")
@RequestMapping("/answer/")
public class AnswerController {

	@Autowired
	AnswerService answerService;
	
	@Autowired
	IssueService issueService;
	
	@Autowired
	UserService userService;
	
	@Autowired
	ExpertService expertService;
	
	@Autowired
	LikeService likeService;
	
	@RequestMapping("insert")
	public String insert(String id,String openId,String issueContent,String image){
		
		
		UserEntity userEntity = userService.findByOpenId(openId);
		if(userEntity.getExpertEntity().getAuditStatus().equals("1")){
			AnswerEntity answerEntity=new AnswerEntity();
			answerEntity.setIssueId(Integer.valueOf(id));
			answerEntity.setAnswerContent(issueContent);
			answerEntity.setExpertId(userEntity.getExpertId());
			answerEntity.setCreateTime(new Date(System.currentTimeMillis()));
			answerEntity.setLikeMark(0);
			answerEntity.setDislikeMark(0);
			answerEntity.setImage(image);
			answerEntity.setStatus("1");
			System.out.println(answerEntity);
			
			int result = answerService.insert(answerEntity);
			if(result==1){
				
				AnswerEntity answer = answerService.findById(answerEntity.getId());
				
				IssueEntity issueEntity=issueService.findById(Integer.valueOf(id));
				
				String touser = issueEntity.getUserEntity().getOpenId();
				
				String url = Constant.REALM_URL +"issue/findById?issueId="+id+"&openId="+touser+"&mark=issue";
				
				Map<String, Map<String, String>> data = new HashMap<String,Map<String, String>>();
				
				Map<String, String> first=new HashMap<String, String>();
				first.put("value", "专家回答成功通知。");
				first.put("color", WeChatConfig.MESSAGE_COLOR);
				
				Map<String, String> keyword1=new HashMap<String, String>();
				keyword1.put("value", String.valueOf(answerEntity.getId()));
				keyword1.put("color", WeChatConfig.MESSAGE_COLOR);
				
				
				Map<String, String> keyword2=new HashMap<String, String>();
				if(answer.getAnswerContent().contains(".mp3")){
					keyword2.put("value", "【语音回答】");
				}else{
					keyword2.put("value", answer.getAnswerContent());
				}
				keyword2.put("color", WeChatConfig.MESSAGE_COLOR);
				
				Map<String, String> keyword3=new HashMap<String, String>();
				keyword3.put("value", answerEntity.getCreateDateFormat());
				keyword3.put("color", WeChatConfig.MESSAGE_COLOR);
				
				Map<String, String> remark=new HashMap<String, String>();
				remark.put("value", "专家在百忙之中抽空给你解答，点击进入打赏！");
				remark.put("color", WeChatConfig.MESSAGE_COLOR);
				
				data.put("first",first);
				data.put("keyword1",keyword1);
				data.put("keyword2",keyword2);
				data.put("keyword3", keyword3);
				data.put("remark",remark);
				
				Wechat.sendMessage(data,WeChatConfig.ANSWER_FULFILL_NOTICE,touser,url);
				
			}
			
			return "redirect:../user/findByOpenId?openId="+openId;
		}
		return "service/error";
	}
	
	@RequestMapping("findByExpertId")
	public String findByExpertId(Model model){
		int expertId=1;
		
		model.addAttribute("answerList", answerService.findByExpert(expertId));
		
		return "service/answer-record";
	}
	
	@RequestMapping("findAnswerRecordUI")
	public String findAnswerRecordUI(Model model,String openId){
		
		return "service/answer-record";
	}
	
	@RequestMapping("findAnswerRecord")
	public void findAnswerRecord(int page,int size,String openId,HttpServletResponse response){
		
		UserEntity userEntity = userService.findByOpenId(openId);
		List<IssueEntity> issueList=null;
			if(userEntity.getExpertId()!=0){

				Map<String,Integer> map=new HashMap<String,Integer>();
				map.put("expertId", userEntity.getExpertId());
				if(page!=0){
					 int cPage=page;
					 cPage=(cPage-1)*10;
					 map.put("page", cPage);
					 map.put("size", size);
				 }
				issueList=issueService.findRecord(map);
			}
			
			String json = JSON.toJSONString(issueList);
			try {
				response.getWriter().write(json);
				response.flushBuffer();
			} catch (Exception e) {
				System.out.println("JsonError："+e);
			}
			
		}
	
	@RequestMapping("addAnswer")
	public String addAnswer(int id,String issueContent){
		AnswerEntity answerEntity=new AnswerEntity();
		answerEntity.setId(id);
		answerEntity.setAddAnswerContent(issueContent);
		answerEntity.setAddCreateTime(new Date(System.currentTimeMillis()));
		answerService.addAnswer(answerEntity);
		
		
		return "redirect:../issueType/findAll?mark=service";
	}
	
	@RequestMapping("delete")
	@ResponseBody
	public int delete(int answerId,int userId,Model model){
		//删除图片与语音
		AnswerEntity answerEntity = answerService.findById(answerId);
		if(answerEntity.getAnswerContent().contains(".mp3")){
			String mp3 = answerEntity.getAnswerContent().split(";")[0];
			mp3=mp3.replace("..", Constant.UPLOAD_SYSTEM_URL);
			System.out.println("mp3:>>>"+mp3);
			File file=new File(mp3);
			file.delete();
		}
		
		if(answerEntity.getImage()!=""){
			String image[] = answerEntity.getImage().split(";");
			for(int i=0;i<image.length;i++){
				image[i]=image[i].replace("..", Constant.UPLOAD_SYSTEM_URL);
				System.out.println("image:>>>"+image[i]);
				File file=new File(image[i]);
				file.delete();
			}
		}
		
		System.out.println("进入答案删除：>>>"+answerId+"  "+userId);
		int result = answerService.delete(answerId);
		System.out.println("result"+result);
		if(result!=-1){
			LikeEntity likeEntity = new LikeEntity();
			likeEntity.setAnswerId(answerId);
			likeEntity.setUserId(userId);
			
			return likeService.delete(likeEntity);
		}
		
		
		return -1;
	}
	
	@RequestMapping("findByIssueId")
	public void findByIssueId(int issueId,HttpServletResponse response){
		Map<String, Integer> map = new HashMap<String, Integer>();
		map.put("issueId", issueId);
		List<AnswerEntity> answerEntity = answerService.findByIssueId(map);
		

		  String json = JSON.toJSONString(answerEntity);
			try {
				response.getWriter().write(json);
				response.flushBuffer();
			} catch (Exception e) {
				System.out.println("JsonError："+e);
			}
	}
	
	@RequestMapping("findById")
	public void findById(int expertId,HttpServletResponse response){
		Map<String,Integer> expert=new HashMap<String,Integer>();
		expert.put("expertId", expertId);
		List<IssueEntity> expertList=issueService.findRecord(expert);
		
		 String json = JSON.toJSONString(expertList);
			try {
				response.getWriter().write(json);
				response.flushBuffer();
			} catch (Exception e) {
				System.out.println("JsonError："+e);
			}
		
	}
	
	@RequestMapping("updateStatus")
	public String updateStatus(AnswerEntity answerEntity){
		AnswerEntity answer = answerService.findById(answerEntity.getId());
		System.out.println(answerService.updateStatus(answerEntity));
		return "redirect:../serve/answer.jsp?issueId="+answer.getIssueId();
	}
}
